//
//  NSString+Tool.m
//  SLDemo
//
//  Created by bocai on 2016/12/2.
//  Copyright © 2016年 Heracles. All rights reserved.
//

#import "NSString+Tool.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (Tool)

- (NSString *)t_md5String
{
    const char *string = self.UTF8String;
    int length = (int)strlen(string);
    unsigned char bytes[CC_MD5_DIGEST_LENGTH];
    CC_MD5(string, length, bytes);
    
    return [self t_stringFromBytes:bytes length:CC_MD5_DIGEST_LENGTH];
}

- (NSString *)t_sha1String
{
    const char *string = self.UTF8String;
    int length = (int)strlen(string);
    unsigned char bytes[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(string, length, bytes);
    
    return [self t_stringFromBytes:bytes length:CC_SHA1_DIGEST_LENGTH];
}

- (NSString *)t_stringFromBytes:(unsigned char *)bytes
                         length:(NSInteger)length
{
    NSMutableString *mutableString = [@[] mutableCopy];
    for (NSInteger i = 0; i < length; i++) {
        [mutableString appendFormat:@"%02x", bytes[i]];
    }
    return [mutableString copy];
}

- (NSDate *)t_dateWithDateFormat:(NSString *)dateFormat
{
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    dateFormatter.dateFormat = dateFormat ? dateFormat : T_DateFormat_yyyy_MM_dd_HH_mm;
    return [dateFormatter dateFromString:self];
}

- (BOOL)t_isValidWithRegexString:(NSString *)regexString
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexString];
    return [predicate evaluateWithObject:self];
}

- (BOOL)t_isValidMobilePhoneNumber
{
    //  手机号以13，15，18，17开头
    NSString *phoneRegex = @"^1(3[0-9]|5[0-35-9]|8[025-9]|70|77)\\d{8}$";
    return [self t_isValidWithRegexString:phoneRegex];
}

- (BOOL)t_isValidLicensePlateNumber
{
    NSString *carRegex =@"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    return [self t_isValidWithRegexString:carRegex];
}

- (NSString *)t_trimmingSpaceString
{
    return [self stringByReplacingOccurrencesOfString:@" " withString:@""];
}

@end
